﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using phones.Model;

namespace phones.Repository
{
    public static class DataLayerStatics
    {
        private static phonesEntities _context;
        /// <summary>
        /// Общий контекст данных для всех репозиториев
        /// </summary>
        public static phonesEntities Context
        {
            get
            {
                if (_context == null)
                {
                    _context = NewContext();
                }
                return _context;
            }
        }

        /// <summary>
        /// Создает новый контекст данных
        /// </summary>
        /// <returns>Новый настроенный контекст данных</returns>
        public static phonesEntities NewContext()
        {

            phonesEntities context =
                !string.IsNullOrEmpty(ContextConnectionString.Trim()) ?
                new phonesEntities(ContextConnectionString) :
                    new phonesEntities();

            context.ContextOptions.LazyLoadingEnabled = true;
            context.ContextOptions.ProxyCreationEnabled = false;
            return context;

        }

        private static string _contextConnectionString = string.Empty;

        public static string ContextConnectionString
        {
            get { return _contextConnectionString; }
            set
            {
                bool changed = _contextConnectionString != value;
                _contextConnectionString = value;
                if (_context != null && changed) _context = null;
                if (changed) _context = NewContext();
            }
        }
    }
}
